<template>
    <div class="activily-info-control">
        <el-scrollbar
            id="activilyInfoForm"
            ref="activilyScrollBarRef"
            class="activily-info-form main"
            @scroll="handleScrollChange">
            <!-- 步骤条 -->
            <activily-step v-model="stepValue" :options="stepOptions" />
            <!-- 表单控件 -->
            <div class="control-form">
                <div v-show="stepValue === 0">
                    <!-- 步骤一：基本信息 -->
                    <basic-info-form ref="basicInfoFormRef" @change-phone-tabs="changeActivilyTabsActived" />
                </div>
                <div v-show="stepValue === 1">
                    <!-- 步骤二：奖品及群聊 -->
                    <prize-group-form ref="prizeGroupFormRef" />
                </div>
                <div v-show="stepValue === 2">
                    <!-- 步骤三：分享设置 -->
                    <share-settings-form ref="shareSettingsFormRef" />
                </div>
                <div v-show="stepValue === 3">
                    <!-- 步骤四：高级设置 -->
                    <advanced-settings-form
                        ref="advancedSettingsFormRef"
                        @change-phone-tabs="changeActivilyTabsActived" />
                </div>
            </div>
        </el-scrollbar>
        <article class="activity-phone main">
            <activity-phone ref="activityPhoneRef" v-model:phone-preview-index="phonePreviewIndex" />
        </article>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, inject, nextTick, markRaw } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { WarningFilled } from '@element-plus/icons-vue';

import { createGroupFissionNew, editGroupFissionInfo } from '@/api/smartMarketing/drainage/groupFission';

import activilyStep from './activily-step.vue';
import activityPhone from './activity-phone.vue';

import basicInfoForm from './control-form/basic-info-form.vue';
import prizeGroupForm from './control-form/prize-group-form.vue';
import shareSettingsForm from './control-form/share-settings-form.vue';
import advancedSettingsForm from './control-form/advanced-settings-form.vue';

import { getParamsByFormModel, stepValue } from './utils/paramsManager';
import { IActivilyTabsActived, IPageType } from './utils/interface';

const router = useRouter();
const route = useRoute();

/** 进行中、结束的情况下禁用 */
const pageType: IPageType | undefined = inject('pageType');

/* ----------------------------表单校验-start---------------------------- */
interface IFormRef {
    validate: () => boolean;
    /** 分享设置，设置欢迎语内容 */
    setWelcomeInfo?: (data: any, groupData: any) => unknown;
}
/** 基础信息 */
const basicInfoFormRef = ref<IFormRef>();
/** 奖品及群聊 */
const prizeGroupFormRef = ref<IFormRef>();
/** 分享设置 */
const shareSettingsFormRef = ref<IFormRef>();
/** 高级设置 */
const advancedSettingsFormRef = ref<IFormRef>();

/* ----------------------------表单校验-end---------------------------- */

/* ----------------------------样机-start---------------------------- */
const activityPhoneRef = ref();

/** 更改样机标签栏tabs选中的 */
const changeActivilyTabsActived = (val: IActivilyTabsActived | string) => {
    activityPhoneRef.value?.setActivilyTabsActived(val);
};

/** 设置海报定位信息 */
const setPosterInfo = (data: any) => {
    activityPhoneRef.value?.setPostersInfo(data);
};
/* ----------------------------样机-end---------------------------- */

/* ----------------------------步骤条-start---------------------------- */
/** 滚动条ref实例 */
const activilyScrollBarRef = ref();
/**
 * @description 步骤条配置项
 */
const stepOptions = reactive([
    { label: '基础信息' },
    { label: '奖品及群聊' },
    { label: '分享设置' },
    { label: '高级设置' }
]);

/**
 * 下一步
 */
const next = async () => {
    try {
        // 校验步骤
        const formRefs = [basicInfoFormRef, prizeGroupFormRef, shareSettingsFormRef, advancedSettingsFormRef];
        await formRefs[stepValue.value].value?.validate();
        if (stepValue.value >= stepOptions.length - 1) {
            return;
        }
        stepValue.value++;
        await nextTick();
        activilyScrollBarRef.value?.setScrollTop(0);
    } catch (err: any) {
        // 校验失败给出提示
        const [[errMessage]]: any = Object.values(err);
        ElMessage.warning({
            grouping: true,
            message: errMessage?.message,
            repeatNum: 1
        });
    }
};
/**
 * 上一步
 */
const prev = async () => {
    if (stepValue.value <= 0) {
        return;
    }
    stepValue.value--;
    await nextTick();
    activilyScrollBarRef.value?.setScrollTop(0);
};
/**
 * 取消
 */
const cancel = async () => {
    try {
        await ElMessageBox.confirm('确定要放弃编辑该活动吗？', '提示', {
            customClass: 'messbox-confrim',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            icon: markRaw(WarningFilled)
        });
        router.back();
    } catch {
        // 取消关闭, 为了控制台不报错，不做任何处理
    }
};
/**
 * 保存
 */
const save = async () => {
    // 进行全部校验
    try {
        await basicInfoFormRef.value?.validate();
        await prizeGroupFormRef.value?.validate();
        await shareSettingsFormRef.value?.validate();
        await advancedSettingsFormRef.value?.validate();
    } catch (err: any) {
        // 校验失败给出提示
        const [[errMessage]]: any = Object.values(err);
        ElMessage.warning({
            grouping: true,
            message: errMessage?.message,
            repeatNum: 1
        });
        return;
    }
    // 获取传给后端的字段
    const params = getParamsByFormModel();

    // 获取海报位置信息
    const poster = activityPhoneRef.value?.getPostersInfo();
    params.poster = {
        ...params.poster,
        ...poster
    };

    // 新增复制的时候，不需要id, 编辑后再次编辑欢迎语需要原来的id。
    if (pageType?.new || pageType?.copy) {
        params.groupchat_welcome.welcome_friend_id = undefined;
    }

    // 创建/编辑接口
    let saveGroupFission = createGroupFissionNew,
        successMessage = '创建成功';

    // 编辑的情况下换接口，再次过滤数据等
    if (pageType?.edit) {
        saveGroupFission = editGroupFissionInfo;
        successMessage = '编辑成功';
        // 可能还要过滤数据
        params.activity_id = params.id;
        await ElMessageBox.confirm(
            '确认要修改该活动信息吗？修改后历史数据不会变更，例如：已发放奖品为原奖品、已添加用户标签不会变更、已入群用户信息不会变更等',
            '提示',
            {
                customClass: 'messbox-confrim',
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                icon: markRaw(WarningFilled)
            }
        );
    }

    try {
        // 创建群裂变
        const res: {
            /** 群模板是否达到上限， 1: 未达到，2 达到 */
            group_templates_upper: 1 | 2;
        } = await saveGroupFission({
            ...params,
            official_account_id: route.query?.official_account_id
        });
        // 群模板达到上限
        if (res.group_templates_upper === 2) {
            return handleGroupTemplatesUpper();
        }
        ElMessage.success(successMessage);
        router.push({
            path: '/smartMarketing/drainage/groupFission',
            query: { group_id: basicInfoFormRef.value.formParams.group_id }
        });
    } catch {
        // ElMessage.error();
    }
};

/** 群模版创建达到上限提示 */
const handleGroupTemplatesUpper = async () => {
    await ElMessageBox.alert(
        '因企微限制，企业创建入群欢迎语达到上限，请前往入群欢迎语模块删除部分无效欢迎语后再保存活动',
        '提示',
        {
            customClass: 'messbox-confrim',
            confirmButtonText: '前往入群欢迎语',
            type: 'warning',
            icon: markRaw(WarningFilled)
        }
    );
    window.open(`${location.origin}/channel/qwbasicoperation/welcomegroup`);
};

// 设置欢迎语内容
const setWelcomeInfo = (data: any, groupData: any) => {
    shareSettingsFormRef.value?.setWelcomeInfo?.(data, groupData);
};

// 抛出方法给外部调用
defineExpose({
    next,
    prev,
    cancel,
    save,
    setWelcomeInfo,
    setPosterInfo
});
/* ----------------------------步骤条-end---------------------------- */

/* ----------------------------滚动-start---------------------------- */

/**
 * 手机样机预览的索引
 */
const phonePreviewIndex = ref(0);

const handleScrollChange = (val: { scrollTop: number }) => {
    // 只有在第三步滚动才判断
    if (stepValue.value !== 2) {
        return;
    }
    try {
        const staffMaterialContent = document.querySelector('#staffMaterialContent');
        const groupMaterialContent = document.querySelector('#groupMaterialContent');
        const activilyInfoForm: any = document.querySelector('#activilyInfoForm');
        const posterFormItem = document.querySelector('#posterFormItem');
        const staffRect: any = staffMaterialContent?.getClientRects()[0];
        const groupRect: any = groupMaterialContent?.getClientRects()[0];
        const posterRect: any = posterFormItem?.getClientRects()[0];
        const scrollViewRect: any = activilyInfoForm?.querySelector('.el-scrollbar__view')?.getClientRects()[0];

        // 优先判断是否滚动到了底部
        if (val.scrollTop + activilyInfoForm?.clientHeight > scrollViewRect?.height) {
            phonePreviewIndex.value = 2;
            return;
        }
        /**
         * @description DOM_TOP px 是一个安全的距离。dom移动至这个距离时做切换体验回稍微好点
         */
        const DOM_TOP = 220;
        // 依次查找第一个距离顶部为px的dom元素。1、添加员工推送欢迎语，2、加入群聊推送欢迎语，3、分享海报设置
        const index = [staffRect?.top, groupRect?.top, posterRect?.top].findIndex(item => item >= DOM_TOP);

        // phonePreviewIndex 这个变量在activity-phone组件判断了欢迎语组件的索引
        phonePreviewIndex.value = index;
    } catch {
        // 一旦报错，就到第一个
        phonePreviewIndex.value = 0;
    }
};
/* ----------------------------滚动-end---------------------------- */
</script>
<style lang="scss" scoped>
@import './styles/activily-info';
@import './styles/control-form';
</style>
